﻿using System;
using System.Diagnostics;
using System.Globalization;

namespace Plugins.Samples
{
    using Controls;
    using Interfaces;
    using Internal;

    [Serializable]
    public partial class PiChildWindow : PluginWindow
    {
        public PiChildWindow()
        {
            InitializeComponent();
        }

        protected override IPluginWorkItem Create()
        {
            return PiWorkItemManager.Create(this, Digits, Length);
        }
        
        protected override bool CanStart { get { return true; } }
        protected override bool CanStop { get { return true; } }
        protected override bool CanReset { get { return true; } }

        private const int Digits = 10000;
        private const int Length = 1000;

        protected override void Initialize()
        {
            base.Initialize();
            PluginControlHelper.Action<PluginGradientControl>(this.gradientControl1, control =>
            {
                control.BeginUpate();
                control.Min = 0;
                control.Max = 100;
                control.GraphOpacity[0] = 0.25;
                control.ProgressPosition = 0;
                control.Theme = GradientColorThemeType.White;
                control.ProgressBarOpacity = 0.25;
                control.TextBufferLength = 100;
                control.GrapthBufferLength = 1000;
                control.EndUpdate();
                control.Refresh();
            });
        }

        private static object _sync = new object();

        public void AddWatch(long milliseconds)
        {
            double[] data = new double[1] { milliseconds };
            PluginControlHelper.Action<PluginGradientControl>(this.gradientControl1, control =>
            {
                control.AddGrapthPoints(data);
                control.ClearText();
                control.WriteLine(milliseconds.ToString());
                control.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0, 10:0.}", control.GetAverageValue(0)));
            });
        }

        private Stopwatch sw = new Stopwatch();
        private void PiWindow_NotifyStart(object sender, EventArgs e)
        {
            sw.Reset();
            sw.Start();
        }

        private void PiWindow_NotifyStop(object sender, EventArgs e)
        {
            sw.Stop();
            string milliseconds = sw.Elapsed.ToString();
            PluginControlHelper.Action<PluginGradientControl>(this.gradientControl1, control =>
            {
                control.WriteLine(milliseconds);
            });
        }

        private void PiWindow_Load(object sender, EventArgs e)
        {
            LoadWindowState();
        }

        private void PiWindow_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            UnloadWindowState();
        }
    }
}
